/**
* @program: src
*
* @description:
*
* @author: Mr.chen
*
* @create: 2022-04-12 17:19
**/
package tracing

import (
	"do_demo/srv/common/core/trace"
	"github.com/gin-gonic/gin"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/propagation"
	semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
	oteltrace "go.opentelemetry.io/otel/trace"
)

// TracingHandler return a middleware that process the opentelemetry.
func TracingHandler()  gin.HandlerFunc {
	return func(c *gin.Context) {
		propagator := otel.GetTextMapPropagator()
		tracer := otel.GetTracerProvider().Tracer(trace.TraceName)
		r := c.Request
		w := c.Writer
		ctx := propagator.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
		spanName := ""
		if len(spanName) == 0 {
			spanName = r.URL.Path
		}
		spanCtx, span := tracer.Start(
			ctx,
			spanName,
			oteltrace.WithSpanKind(oteltrace.SpanKindServer),
			oteltrace.WithAttributes(semconv.HTTPServerAttributesFromHTTPRequest(
				"logic-api", spanName, r)...),
		)
		defer span.End()
		// convenient for tracking error messages
		sc := span.SpanContext()
		if sc.HasTraceID() {
			w.Header().Set(trace.TraceIdKey, sc.TraceID().String())
		}
		c.Request = r.WithContext(spanCtx)
		// 处理请求
		c.Next()
		//next.ServeHTTP(w, r.WithContext(spanCtx))
	}
}
